package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.beust.jcommander.internal.Nullable;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ghp
 * @title 登录拦截器
 * @description
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    /**
     * 前置拦截器，用于判断用户是否登录
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */

    private StringRedisTemplate stringRedisTemplate;

    /**使用函数对其进行注解(因为LoginInterceptor类的对象不是由spring创建的，而是手动创建的)
     * spring创建的对象会自动进行依赖注入，手动创建的对象没法使用依赖注入，只能使用构造函数注入(看哪个对象使用了它，就在哪里进行注入)
     * @Resource
     * private StringRedisTemplate stringRedisTemplate;
     * @param stringRedisTemplate
     */
    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate=stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头中的token
        String token=request.getHeader("authorization");

        //判断token是否为空
        if(StrUtil.isBlank(token)){
            return true;
        }
        //2.基于token来获取redis中的用户
        String key=RedisConstants.LOGIN_USER_KEY+token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash()
                .entries(key);

        //3.判断用户是否存在
        if(userMap.isEmpty()){
            return true;
        }

        //4.将查询到的Hash数据转为UserDTO对象
        UserDTO userDTO=BeanUtil.fillBeanWithMap(userMap,new UserDTO(),false);

        //5.存在，保存用户信息到ThreadLocal
        UserHolder.saveUser(userDTO);

        //6.刷新token的有效期
        stringRedisTemplate.expire(key,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);

        //7.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        //移除用户
        UserHolder.removeUser();
    }
}